package com.google.code.p.localspinner.iva;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URLEncoder;
import java.text.MessageFormat;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.google.code.p.localspinner.AppUtils;
import com.google.code.p.localspinner.SearchException;
import com.google.code.p.localspinner.http.UserAgent;
import com.google.code.p.localspinner.model.Item;
import com.google.code.p.localspinner.model.ItemList;

public class MoviesSearch {

  private UserAgent userAgent = new UserAgent();

  private final XmlPullParser pullParser;
  private static final String SEARCH_URL =
    "http://www.videodetective.com/api/topboxoffice.aspx?DeveloperId=481D3EF7-5D1C-44E3-B76B-19ECA5C65A03&PageSize=12&Page=1";

  private static final String BASE_QUERY = "http://gdata.youtube.com/feeds/api/videos?q={0}%20trailer&max-results=1";

  public MoviesSearch() throws SearchException{
    try {
      pullParser = XmlPullParserFactory.newInstance().newPullParser();
    } catch (XmlPullParserException e) {
      throw new SearchException("Unable to initialize xml parser", e);
    }
  }
  
  
  public String getYoutubeTrailer(String query) throws SearchException{
      String url = MessageFormat.format(BASE_QUERY, URLEncoder.encode(query));
      InputStream res = null;
      try {
        res = userAgent.getUrlAsStream(url);
        pullParser.setInput(new InputStreamReader(res));
        return parseTrailerUrl(pullParser);
      } catch (Exception e) {
        throw new SearchException("Search failed", e);
      }finally{
        AppUtils.closeQuietly(res);
      }
  }
  
  private String parseTrailerUrl(XmlPullParser pullParser) throws XmlPullParserException, IOException{
      int eventType = pullParser.getEventType();
      while(eventType != XmlPullParser.END_DOCUMENT){
        if(eventType == XmlPullParser.START_TAG
            && "media:player".equalsIgnoreCase(pullParser.getName())){
            return pullParser.getAttributeValue(null, "url");
        }
        eventType = pullParser.next();
      }
      return null;
  }
  

  public ItemList searchTopMovies() throws SearchException{
    try {
      String result = userAgent.getUrlAsString(SEARCH_URL);
      //XXX this api gives unclean xml, so i need to clean it for them
      for(int i =0; i< result.length(); i++){
        if(result.charAt(i)=='<'){
          result = result.substring(i).replaceAll(">\\s+", ">");
          break;
        }
      }
      pullParser.setInput(new StringReader(result));
      return parseResult(pullParser);
    } catch (Exception e) {
      throw new SearchException("Search failed", e);
    }
  }
  
  private ItemList parseResult(XmlPullParser pullParser) throws XmlPullParserException, IOException{
    ItemList ret = new ItemList();
    ret.setListName("Wheel of Top Movies");
    int eventType = pullParser.getEventType();
    while(eventType != XmlPullParser.END_DOCUMENT){
      if(eventType == XmlPullParser.START_TAG){
          if("item".equalsIgnoreCase(pullParser.getName())){
            String title = null;
            StringBuilder body = new StringBuilder();
            String url = null;
            //children of Result
            while(true){
                if(eventType == XmlPullParser.END_TAG && "item".equalsIgnoreCase(pullParser.getName())){
                    break;
                }
                eventType = pullParser.next(); 
                if(eventType == XmlPullParser.START_TAG){
                  String name = pullParser.getName();
                  if("Title".equalsIgnoreCase(name)){
                    eventType = pullParser.next();
                    if(eventType == XmlPullParser.TEXT){
                      title = AppUtils.nvl(pullParser.getText(), "");
                    }
                  }else if("Description".equalsIgnoreCase(name)){
                    eventType = pullParser.next();
                    if(eventType == XmlPullParser.TEXT){
                      title = AppUtils.nvl(pullParser.getText(), "");
                      title = title.replaceAll("Video$", "");
                    }
                  }else if("Rating".equalsIgnoreCase(name)
                      || "Genre".equalsIgnoreCase(name)){
                    eventType = pullParser.next();
                    if(eventType == XmlPullParser.TEXT){
                      body.append(AppUtils.nvl(name+": "+pullParser.getText()+" ", ""));
                    }
                  }else if("BoxOfficeInMillions".equalsIgnoreCase(name)){
                    eventType = pullParser.next();
                    if(eventType == XmlPullParser.TEXT){
                      body.append(AppUtils.nvl("\nBox office in millions: "+pullParser.getText(), ""));
                    }
                  }
//                  else if("Link".equalsIgnoreCase(name)){
//                    eventType = pullParser.next();
//                    if(eventType == XmlPullParser.TEXT){
//                      url = AppUtils.nvl(pullParser.getText(), "");
//                    }
//                  }                  
                }
                eventType = pullParser.next();
            }
            if(title != null){
              Item item = new Item(title, body.toString());
              item.setUrl(url);
              item.setUrl("http://gdata.youtube.com/feeds/api/videos?q=saw%20v%20trailer&max-results=1&format=6");
              ret.addItem(item);
            }
          }
      }
      eventType = pullParser.next();
    }
    return ret;
  }
  

}
